/*
 * Connectable.java
 *
 * Created on 1 de Outubro de 2007, 20:51
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package Remote;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author Ronaldinho
 */
public abstract class Connectable implements Runnable {    
    
    //portas de comunica��o com os servidores
    protected int receivePort;
    protected int sendPort;
    
    //�ltimo ip remoto a se conectar
    protected String ip;
        
    //�ltima mensagem recebida
    protected Message message;
    
    //Socket que escuta as conex�es com o servidor
    protected ServerSocket listenerSocket; 
    
    protected boolean connectionEnded;
    
    //Construtor
    public Connectable(int receivePort, int sendPort) throws IOException{
        this.receivePort = receivePort;
        this.sendPort = sendPort;
        this.listenerSocket = new ServerSocket(this.receivePort);
        this.connectionEnded = false;
    }

    public int getReceivePort() {
        return receivePort;
    }

    public int getSendPort() {
        return sendPort;
    }

    public ServerSocket getListenerSocket() {
        return listenerSocket;
    }

    public void setSendPort(int sendPort) {
        this.sendPort = sendPort;
    }

    public void setReceivePort(int receivePort) {
        this.receivePort = receivePort;
    }
    
    public void setListenerSocket(ServerSocket listenerSocket) {
        this.listenerSocket = listenerSocket;
    }

    public void setConnectionEnded(boolean connectionEnded) {
        this.connectionEnded = connectionEnded;
    }
    
    //m�todo que envia uma mensagem ao servidor
    protected void enviarMensagem(String ip, Message message) throws IOException{
        Socket s = new Socket(ip, this.sendPort);
        ObjectOutputStream outToServer = new ObjectOutputStream(s.getOutputStream());
        outToServer.writeObject(message);
        s.close();
    }
    
    //m�todo que recebe uma mensagem do servidor
    protected void receberMensagem() throws IOException, ClassNotFoundException{
        Socket s = this.listenerSocket.accept();
        ObjectInputStream inFromServer = new ObjectInputStream(s.getInputStream());
        this.message = ((Message)inFromServer.readObject());
        this.ip = s.getInetAddress().getHostAddress();
        s.close();
    }
    
    protected abstract void conectar();
}